/*
 *  Copyright © 2011 by Rob Cash
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * 
 * BookmarkURIComparator.java
 * 
 * Created on Jul 30, 2011 at 3:23:46 PM
 */
package org.robcash.apps.bookmarksync.util;

import java.util.Comparator;
import org.robcash.apps.bookmarksync.BookmarkSyncException;
import org.robcash.apps.bookmarksync.vo.Bookmark;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Bookmark URI comparator
 * @author Rob Cash
 */
public class BookmarkURIComparator implements Comparator<Bookmark>
{
    /**
     * Bookmark URI Comparator
     */
    public static final Comparator<Bookmark> COMPARATOR = new BookmarkURIComparator();
    
    @SuppressWarnings("unused")
    private static final Logger LOG = LoggerFactory.getLogger(BookmarkURIComparator.class);

    @Override
    public int compare(Bookmark b1, Bookmark b2)
    {
        try
        {
            String uri1 = b1.getURI().toLowerCase().trim();
            String uri2 = b2.getURI().toLowerCase().trim();

            boolean areEqual = uri1.equals(uri2);
            if ( areEqual )
            {
                return 0;
            }

            // See if bookmarks are equal without respect to a trailing /
            boolean uri1EndsInSlash = uri1.endsWith("/");
            boolean uri2EndsInSlash = uri2.endsWith("/");

            if ( uri1EndsInSlash && !uri2EndsInSlash )
            {
                areEqual = uri2.equals(uri1.substring(0, uri1.length()-2));
            }
            else if ( !uri1EndsInSlash && uri2EndsInSlash )
            {
                areEqual = uri1.equals(uri2.substring(0, uri2.length()-2));
            }

            if ( areEqual )
            {
                return 0;
            }
            else
            {
                return uri1.compareTo(uri2);
            }
        }
        catch(BookmarkSyncException e)
        {
            throw new RuntimeException("Compare failed", e);
        }
    }

    
}
